const mongoose = require('mongoose'),
	glob = require('glob'),
	{ resolve } = require('path'),
	db = 'mongodb://localhost/jspang-mall-db'

mongoose.Promise = global.Promise

exports.connect = () => {
  mongoose.set('useCreateIndex', true)
	mongoose.connect(db)

	let maxTimes = 0

	return new Promise((resolve, reject) => {
		mongoose.connection.on('disconnected', () => {
			console.log('********数据库连接失败********')

			if (maxTimes < 3) {
				maxTimes++
				mongoose.connect(db)
			} else {
				reject('数据连接失败...')
				// throw new Error('数据连接失败...')
			}
		})

		mongoose.connection.on('error', error => {
			console.log('********数据库连接失败********')
			if (maxTimes < 3) {
				maxTimes++
				mongoose.connect(db)
			} else {
				reject('数据连接失败：' + error)
				// throw new Error('数据连接失败：' + error)
			}
		})

		mongoose.connection.once('open', () => {
			console.log('Database jspang-mall-db connected successfully!')
			resolve()
		})
	})
}

exports.initSchemas = () => {
	glob.sync(resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}
